package io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class OverlapsReader {
	private String[] m_genes;

	public OverlapsReader(InputStream input) throws IOException {
			m_genes = preProcessSourceLines(input);
	}

	public String getGeneAt(int index) {
		if (index < m_genes.length) {
			return m_genes[index];
		} else {
			throw new IllegalArgumentException("Illegal index of gene used..."
					+ index);
		}
	}

	public int numberOfGenes() {
		return m_genes.length;
	}

	private String[] preProcessSourceLines(InputStream in) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		List lineList = new ArrayList();

		String line;
		String extendedLine = "";
		int added = 0;
		int notAdded = 0;
	
		while ((line = reader.readLine()) != null) {			
			if ((line.length() > 0) && (line.charAt(0) != '>')) {
				line = line.trim();
				extendedLine = extendedLine.concat(line);
			} else {
				if (line.length() > 0 && (line.charAt(0) == '>') && (extendedLine.length()>0)) {
					lineList.add(extendedLine.toUpperCase());
					added = added + 1;
					extendedLine = "";

				} 
			}
		}

		if (true) {
			lineList.add(extendedLine.toUpperCase());
			added = added + 1;
		} else {
			notAdded = notAdded + 1;
		}

		reader.close();

		 //System.out.println("added="+ added);
		// System.out.println("not added="+ notAdded);

		
		return (String[]) lineList.toArray(new String[lineList.size()]);
	}
}
